#include "List.h"

List* BuyNode(SLDataType n)
{
	List* ret = (List*)malloc(sizeof(List));
	if (ret == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	ret->next = NULL;
	ret->num = n;
	return ret;
}

void Print(List* p)
{
	assert(p);
	while (p)
	{
		printf("%d->", p->num);
		p = p->next;
	}
	printf("NULL\n");
}

void PushBack(List** p, SLDataType n)
{
	List* ret = BuyNode(n);
	if (*p == NULL)
	{
		*p = ret;
		return;
	}
	else
	{
		List* ph = *p;
		while (ph->next)
		{
			ph = ph->next;
		}
		ph->next = ret;
	}
}

void PopBack(List** p)
{
	assert(*p);
	if ((*p)->next == NULL)
	{
		free(*p);
		*p = NULL;
		return;
	}
	List* ret = *p;
	while (ret->next->next)
	{
		ret = ret->next;
	}
	free(ret->next);
	ret->next = NULL;
}

void PushFront(List** p, SLDataType n)
{
	List* ret = BuyNode(n);
	ret->next = *p;
	*p = ret;
}

void PopFront(List** p)
{
	assert(*p);
	List* ret = (*p)->next;
	free(*p);
	*p = ret;
}

List* Find(List* p, SLDataType n)
{
	assert(p);
	List* ret = p;
	while (ret)
	{
		if (ret->num == n)
		{
			return ret;
		}
		ret = ret->next;
	}
	return NULL;
}

void Insert(List* pos, SLDataType n)
{
	assert(pos);
	List* ret = BuyNode(n);
	if (pos->next == NULL)
	{
		pos->next = ret;
	}
	else
	{
		List* p = pos->next;
		pos->next = ret;
		ret->next = p;
	}
}

void Erase(List* pos)
{
	assert(pos);
	assert(pos->next);
	List* p = pos->next->next;
	free(pos->next);
	pos->next = p;
}

void Destory(List* p)
{
	assert(p);
	List* pos = p;
	while (p)
	{
		p = p->next;
		free(pos);
		pos = p;
	}
}
